package com.ringtheweb.serviceprovider.weather.core;

import static com.ringtheweb.serviceprovider.weather.core.LocationTreeDiscoveringEvents.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ringtheweb.event.Events;
import com.ringtheweb.event.Observer;
import com.ringtheweb.serviceprovider.weather.model.Location;

@Component("locationTreeObserver")
public class LocationTreeObserver implements Observer {

	private static Log LOG = LogFactory.getLog(LocationTreeObserver.class);
	
	@Autowired
	private LocationTreePersister locationTreePersister;
	
	public LocationTreeObserver() {
		Events.instance().registerListener(AFTER_CURRENT_RETRIEVAL.toString(), this);
		Events.instance().registerListener(BEFORE_CURRENT_RETRIEVAL.toString(), this);
		Events.instance().registerListener(AFTER_LAST_CHILD_RETRIEVAL.toString(), this);
		Events.instance().registerListener(AFTER_NEXT_CHILD_RETRIEVAL.toString(), this);
	}

	@Override
	public void onEvent(String event, Object... parameters) {
		LocationTreeDiscoveringEvents discoveringEvent = null;
		try {
			discoveringEvent = LocationTreeDiscoveringEvents.valueOf(event);
		}
		catch(Throwable t) {
			LOG.error(String.format("Event {0} does not exist", event), t);
			return;
		}
		switch (discoveringEvent) {
		case BEFORE_CURRENT_RETRIEVAL:
			locationTreePersister.beforeRetrieval((Location)parameters[0]);
			break;		
		case AFTER_CURRENT_RETRIEVAL:
			locationTreePersister.afterRetrieval((Location)parameters[0]);
			break;
		case AFTER_NEXT_CHILD_RETRIEVAL:
			locationTreePersister.afterNextChild((Location)parameters[0], (Location)parameters[1]);
			break;
		case AFTER_LAST_CHILD_RETRIEVAL:
			locationTreePersister.afterLastChild((Location)parameters[0]);
			break;
		default:
			break;
		}
			
		
	}

}
